#!/bin/bash

# Excel导入功能验证脚本
# 用于验证Excel导入解析、嵌入、向量存储及导入记录管理功能

set -e

echo "🚀 开始验证Excel导入功能..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置
BASE_URL="http://localhost:8080"
API_BASE="${BASE_URL}/api/v1/excel-embedding"

# 检查服务是否运行
check_service() {
    echo -e "${BLUE}📡 检查服务状态...${NC}"
    
    if curl -s "${BASE_URL}/actuator/health" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ 服务正在运行${NC}"
    else
        echo -e "${RED}❌ 服务未运行，请先启动应用${NC}"
        echo "启动命令: mvn spring-boot:run -pl enplatform-assistant-starter"
        exit 1
    fi
}

# 测试文件上传
test_file_upload() {
    echo -e "${BLUE}📤 测试Excel文件上传...${NC}"
    
    # 创建测试Excel文件（如果不存在）
    TEST_FILE="document/template/元模型数据202506181726.xlsx"
    
    if [ ! -f "$TEST_FILE" ]; then
        echo -e "${YELLOW}⚠️  测试文件不存在: $TEST_FILE${NC}"
        echo "请确保测试文件存在"
        return 1
    fi
    
    echo "上传文件: $TEST_FILE"
    
    # 上传文件
    UPLOAD_RESPONSE=$(curl -s -X POST \
        -F "file=@${TEST_FILE}" \
        -F "createdBy=test-user" \
        "${API_BASE}/upload")
    
    echo "上传响应: $UPLOAD_RESPONSE"
    
    # 解析响应
    SUCCESS=$(echo "$UPLOAD_RESPONSE" | jq -r '.success // false')
    IMPORT_RECORD_ID=$(echo "$UPLOAD_RESPONSE" | jq -r '.importRecordId // ""')
    
    if [ "$SUCCESS" = "true" ] && [ -n "$IMPORT_RECORD_ID" ]; then
        echo -e "${GREEN}✅ 文件上传成功，导入记录ID: $IMPORT_RECORD_ID${NC}"
        echo "$IMPORT_RECORD_ID" > /tmp/import_record_id.txt
        return 0
    else
        echo -e "${RED}❌ 文件上传失败${NC}"
        return 1
    fi
}

# 测试导入记录查询
test_import_records() {
    echo -e "${BLUE}📋 测试导入记录查询...${NC}"
    
    # 查询导入记录列表
    RECORDS_RESPONSE=$(curl -s "${API_BASE}/imports?page=0&size=5")
    echo "导入记录列表: $RECORDS_RESPONSE"
    
    SUCCESS=$(echo "$RECORDS_RESPONSE" | jq -r '.success // false')
    
    if [ "$SUCCESS" = "true" ]; then
        TOTAL_ELEMENTS=$(echo "$RECORDS_RESPONSE" | jq -r '.totalElements // 0')
        echo -e "${GREEN}✅ 导入记录查询成功，总记录数: $TOTAL_ELEMENTS${NC}"
        return 0
    else
        echo -e "${RED}❌ 导入记录查询失败${NC}"
        return 1
    fi
}

# 测试导入记录详情查询
test_import_record_detail() {
    echo -e "${BLUE}🔍 测试导入记录详情查询...${NC}"
    
    if [ ! -f "/tmp/import_record_id.txt" ]; then
        echo -e "${YELLOW}⚠️  没有可用的导入记录ID${NC}"
        return 1
    fi
    
    IMPORT_RECORD_ID=$(cat /tmp/import_record_id.txt)
    
    # 查询导入记录详情
    DETAIL_RESPONSE=$(curl -s "${API_BASE}/imports/${IMPORT_RECORD_ID}")
    echo "导入记录详情: $DETAIL_RESPONSE"
    
    SUCCESS=$(echo "$DETAIL_RESPONSE" | jq -r '.success // false')
    
    if [ "$SUCCESS" = "true" ]; then
        STATUS=$(echo "$DETAIL_RESPONSE" | jq -r '.data.status // ""')
        TOTAL_RECORDS=$(echo "$DETAIL_RESPONSE" | jq -r '.data.totalRecords // 0')
        SUCCESS_RECORDS=$(echo "$DETAIL_RESPONSE" | jq -r '.data.successRecords // 0')
        echo -e "${GREEN}✅ 导入记录详情查询成功${NC}"
        echo -e "   状态: $STATUS"
        echo -e "   总记录数: $TOTAL_RECORDS"
        echo -e "   成功记录数: $SUCCESS_RECORDS"
        return 0
    else
        echo -e "${RED}❌ 导入记录详情查询失败${NC}"
        return 1
    fi
}

# 测试向量查询
test_vector_search() {
    echo -e "${BLUE}🔍 测试向量搜索...${NC}"
    
    if [ ! -f "/tmp/import_record_id.txt" ]; then
        echo -e "${YELLOW}⚠️  没有可用的导入记录ID${NC}"
        return 1
    fi
    
    IMPORT_RECORD_ID=$(cat /tmp/import_record_id.txt)
    
    # 测试基于导入记录的向量查询
    VECTOR_RESPONSE=$(curl -s "${API_BASE}/imports/${IMPORT_RECORD_ID}/vectors?query=用户姓名&topK=5")
    echo "向量搜索响应: $VECTOR_RESPONSE"
    
    SUCCESS=$(echo "$VECTOR_RESPONSE" | jq -r '.success // false')
    
    if [ "$SUCCESS" = "true" ]; then
        TOTAL_RESULTS=$(echo "$VECTOR_RESPONSE" | jq -r '.totalResults // 0')
        echo -e "${GREEN}✅ 向量搜索成功，结果数量: $TOTAL_RESULTS${NC}"
        return 0
    else
        echo -e "${RED}❌ 向量搜索失败${NC}"
        return 1
    fi
}

# 测试统计信息
test_statistics() {
    echo -e "${BLUE}📊 测试统计信息查询...${NC}"
    
    # 查询统计信息
    STATS_RESPONSE=$(curl -s "${API_BASE}/imports/statistics")
    echo "统计信息: $STATS_RESPONSE"
    
    SUCCESS=$(echo "$STATS_RESPONSE" | jq -r '.success // false')
    
    if [ "$SUCCESS" = "true" ]; then
        TOTAL_IMPORTS=$(echo "$STATS_RESPONSE" | jq -r '.statistics.totalImports // 0')
        SUCCESSFUL_IMPORTS=$(echo "$STATS_RESPONSE" | jq -r '.statistics.successfulImports // 0')
        echo -e "${GREEN}✅ 统计信息查询成功${NC}"
        echo -e "   总导入数: $TOTAL_IMPORTS"
        echo -e "   成功导入数: $SUCCESSFUL_IMPORTS"
        return 0
    else
        echo -e "${RED}❌ 统计信息查询失败${NC}"
        return 1
    fi
}

# 清理临时文件
cleanup() {
    rm -f /tmp/import_record_id.txt
}

# 主函数
main() {
    echo -e "${BLUE}🎯 Excel导入功能完整验证${NC}"
    echo "=================================="
    
    # 检查依赖
    if ! command -v curl &> /dev/null; then
        echo -e "${RED}❌ curl 命令未找到，请安装 curl${NC}"
        exit 1
    fi
    
    if ! command -v jq &> /dev/null; then
        echo -e "${RED}❌ jq 命令未找到，请安装 jq${NC}"
        exit 1
    fi
    
    # 执行测试
    FAILED_TESTS=0
    
    check_service || ((FAILED_TESTS++))
    
    echo ""
    test_file_upload || ((FAILED_TESTS++))
    
    echo ""
    test_import_records || ((FAILED_TESTS++))
    
    echo ""
    test_import_record_detail || ((FAILED_TESTS++))
    
    echo ""
    test_vector_search || ((FAILED_TESTS++))
    
    echo ""
    test_statistics || ((FAILED_TESTS++))
    
    # 清理
    cleanup
    
    # 总结
    echo ""
    echo "=================================="
    if [ $FAILED_TESTS -eq 0 ]; then
        echo -e "${GREEN}🎉 所有测试通过！Excel导入功能正常工作${NC}"
        exit 0
    else
        echo -e "${RED}❌ $FAILED_TESTS 个测试失败${NC}"
        exit 1
    fi
}

# 运行主函数
main "$@"
